/**
 * 
 * @param {*} date 
 * @param {*} type date/time/datetime 
 */
const formatTime = (date,type) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  if(type=='date'){
    return [year, month, day].map(formatNumber).join('-');
  }else if(type == 'time'){
    return [hour, minute, second].map(formatNumber).join(':');
  }else if(type == 'all'){
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute,second].map(formatNumber).join(':')
  }else{
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
  }
}

//获取一周前和一个月前的日期
const timeSlot = date1 =>{
  const date = new Date(date1);
  // const nowYear  = date.getFullYear()
  // const nowMonth  = date.getMonth()
  // const nowDay = date.getDate()
  // const hour = date.getHours()
  // const minute = date.getMinutes()
  // const second = date.getSeconds()
  // const nowDayOfWeek = date.getDay(); //今天是本周的第几天
  let date2 = new Date(date);
  date2.setDate(new Date(date.getDate() - 7));
  let date3 = new Date(date);
  date3.setDate(new Date(date.getDate() - 30));

  let weekS = formatDate(date2);
  let weekE = formatDate(date);
  let monthS = formatDate(date3);
  let monthE = formatDate(date);

  //获取当月的天数
  // let monthStartDate = new Date(nowYear, nowMonth, 1);
  // let monthEndDate = new Date(nowYear, nowMonth + 1, 1);
  // let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);

  // let weekS = formatDate(new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1));
  // let weekE = formatDate(new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek + 1)));
  // let monthS = formatDate(new Date(nowYear, nowMonth, 1));
  // let monthE = formatDate(new Date(nowYear, nowMonth, days));
  
  return{
    'week':[weekS,weekE],
    'month':[monthS,monthE]
  }
}

const formatDate = (date) => {
  let myyear = date.getFullYear();
  let mymonth = date.getMonth() + 1;
  let myweekday = date.getDate();
  return [myyear, mymonth, myweekday].map(formatNumber).join('-');
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//判断两个时间的大小
const judgeDate = (date1,date2) => {
  date1 = date1.toString().replace(/-/g,"/");
  date2 = date2.toString().replace(/-/g,"/");
  let a1 = new Date(date1).getTime();
  let a2 = new Date(date2).getTime();
  return a1>a2;
}

module.exports = {
  formatTime: formatTime,
  timeSlot:timeSlot,
  judgeDate,
}
